package com.yswee.mallnavi.model.info;


import com.yswee.framework.data.BaseArrayData;
import com.yswee.framework.data.parser.IParser;
import com.yswee.framework.net.ITaskContext;
import com.yswee.framework.net.http.Callback;
import com.yswee.mallnavi.context.ApiConstant;
import com.yswee.mallnavi.entity.ArrayData;
import com.yswee.mallnavi.entity.info.CouponEntity;
import com.yswee.mallnavi.model.BaseListModel;
import com.yswee.mallnavi.parser.BaseListGsonParser;

import org.json.JSONArray;
import org.json.JSONObject;

public class CouponListModel extends BaseListModel<CouponEntity> {

	private String mCategoryId;

	public void setParams(String categoryId) {
		mCategoryId = categoryId;
	}

	public CouponListModel(ITaskContext context) {
		super(context);
	}

	@Override
	protected IParser<BaseArrayData<CouponEntity>> createParser() {
		return new ListParser();
	}
	
	@Override
	protected String getUrl(Callback<BaseArrayData<CouponEntity>> c, int pageIndex) {
		StringBuilder url = new StringBuilder();
		url.append(ApiConstant.API_COUPON_LIST).
			append("?ActivityCategoryId=").append(mCategoryId).
			append("&skipCount=0&maxResultCount=999");
		return url.toString();
	}

	private class ListParser extends BaseListGsonParser<CouponEntity> {
		@Override
		public BaseArrayData<CouponEntity> parseData(String json) {
			mReponseData = json;
			JSONObject jo = asJSONObject(json);
			if(jo != null) {
				mIsOk = true;
				JSONArray ja = jo.optJSONArray("items");
				if(ja != null) {
					CouponEntity t = null;
					ArrayData<CouponEntity> array = new ArrayData<CouponEntity>();
					for(int i = 0; i < ja.length(); i++) {
						try {
							JSONObject jod = ja.getJSONObject(i);
							t = parseDataT(jod.getJSONObject("activity").toString());
						} catch (Exception e) {
							e.printStackTrace();
						}
						if(t != null) {
							array.array.add(t);
						}
					}
					return array;
				}
			} else {
				mIsOk = false;
			}
			return null;
		}
	}

}
